
'use strict';

const Controller = require('egg').Controller;
const fs = require('mz/fs');
const path = require('path');
const pump = require('mz-modules/pump');

let users={};//存储所有客户端的socketid

class chatControllerController extends Controller {
   //连接数据库，存储socket.io
    async login(){
        const { ctx, app } = this;
        const message = ctx.args[0];
        console.log(message)
        let user_id=message.userid;
        const key = `user-${user_id}`;
        users[key]=ctx.socket.id;
        // const MAX_TTL = 24 * 60 * 60;// 最大过期时长，兜底用
        // await app.redis.set(key, ctx.socket.id, 'NX','EX', MAX_TTL);
        console.log(users);
    }
  
    //私聊
    async sendFriendMessage() {
            const { ctx, app } = this;
            const message = ctx.args[0];
            let user_id=message.user_id;
            let friend_id=message.friend_id;
            let tokey=`user-${friend_id}`;
            console.log("user[key]",users[tokey])
            //数据库存储聊天消息
            let newMessage={
                user_id:message.user_id,
                friend_id:message.friend_id,
                message:message.message,
                types:0,
                time:new Date(),
                state:1
            }
            await this.app.model.Message.create(newMessage);
            //将好友未读消息数+1
            let friendDetail=await this.app.model.Friend.findOne({where:{user_id:friend_id,friend_id:user_id}});
            let tip=friendDetail.tip
            console.log(tip)
            tip++;
            console.log(tip)
            await this.app.model.Friend.update({lasttime:new Date()},{ where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]}});
            await this.app.model.Friend.update({tip:tip},{ where:{user_id:friend_id,friend_id:user_id}}); 
            console.log(tip)
            await app.io.of('/').sockets[users[tokey]].emit('friendRes',message);    
        }
       
        //群聊
        async sendGroupMessage(){
            const { ctx, app } = this;
            const message = ctx.args[0];
            console.log(message);
            let user_id=message.user_id;
            let group_id=message.group_id;
           
            console.log("group_id",group_id)

            let newGroupMessage={
                group_id:group_id,
                user_id:user_id,
                types:0,
                time:new Date(),
                message:message.message,
            }
            //查找所有群成员socketid
            let groupMembers = await this.app.model.GroupMember.findAll({where:{group_id:group_id}})
            console.log(groupMembers);
            let groupMembersId=[];
            for(let i of groupMembers){
                groupMembersId.push(i.user_id);
            }
            console.log(groupMembersId)
            
            //存储群聊记录
            await this.app.model.GroupMessage.create(newGroupMessage);
            //将所有群成员未读消息数+1
            for(let id of groupMembersId){
                await this.app.model.GroupMember.update({lasttime:new Date()},{where:{group_id:group_id,user_id:id}});
                let groupMemberDeatil = await this.app.model.GroupMember.findOne({where:{group_id:group_id,user_id:id}});
                let tip = groupMemberDeatil.tip;
                tip++;
                if(id!==user_id){
                  await this.app.model.GroupMember.update({tip:tip},{where:{group_id:group_id,user_id:id}});  
                }
            }
            //向所有群成员推送消息推送信息
            for(let n of groupMembersId){
                let tokey=`user-${n}`;
                await app.io.of('/').sockets[users[tokey]].emit('groupRes',message);
            }
        }

        //好友图片传输
        async sendFriendImage(){
            const { ctx,app } = this;
            let user_id = this.ctx.cookies.get('userid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let friend_id = this.ctx.cookies.get('friendid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let name = this.ctx.cookies.get('name',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let imgurl = this.ctx.cookies.get('imgurl',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })

            const file = ctx.request.files[0];//接收文件
            console.log("file",file);
            if (!file) return ctx.throw(404);

            let tokey=`user-${friend_id}`;
            console.log("user[key]",users[tokey])

            const filename = (user_id).toString() + (Date.parse(new Date())).toString() + path.extname(file.filename).toLowerCase();
            const targetPath = path.join(this.config.baseDir, `app/public/img`, filename);
            const source = fs.createReadStream(file.filepath);
            const target = fs.createWriteStream(targetPath);
            
            //上传图片到 public/avatar文件夹
            await pump(source, target);
            ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
            //将图片url存入数据库
            let imageMessage=`/img/${filename}`;

            //数据库存储聊天消息
            let newMessage={
                user_id:user_id,
                friend_id:friend_id,
                message:imageMessage,
                types:1,
                time:new Date(),
                state:1
            };
            await this.app.model.Message.create(newMessage);
            //将好友未读消息数+1
            let friendDetail=await this.app.model.Friend.findOne({where:{user_id:friend_id,friend_id:user_id}});
            let tip=friendDetail.tip
            console.log(tip)
            tip++;
            console.log(tip)
            await this.app.model.Friend.update({lasttime:new Date()},{ where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]}});
            await this.app.model.Friend.update({tip:tip},{ where:{user_id:friend_id,friend_id:user_id}}); 
            console.log(tip)
            let message={
                    //发送方信息
                    user_id:user_id,
                    user:{
                        name:name,
                        imgurl:imgurl
                    },
                    //接收方信息
                    friend_id:friend_id,
                    message:imageMessage
                }
            let fromkey=`user-${user_id}`
            await app.io.of('/').sockets[users[fromkey]].emit('friendRes',message);
            await app.io.of('/').sockets[users[tokey]].emit('friendRes',message);
            this.ctx.body="好友图片传输成功";
        }

        //群聊图片传输
        async sendGroupImage(){
            const { ctx,app } = this;
            const file = ctx.request.files[0];//接收文件
            if (!file) return ctx.throw(404);

            let group_id = this.ctx.cookies.get('groupid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let user_id = this.ctx.cookies.get('userid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let name = this.ctx.cookies.get('name',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let imgurl = this.ctx.cookies.get('imgurl',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })

            const filename = (user_id).toString() + (Date.parse(new Date())).toString() + path.extname(file.filename).toLowerCase();
            const targetPath = path.join(this.config.baseDir, `app/public/img`, filename);
            const source = fs.createReadStream(file.filepath);
            const target = fs.createWriteStream(targetPath);
            
            //上传图片到 public/img文件夹
            await pump(source, target);
            ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
            //将图片url存入数据库
            let imageMessage=`/img/${filename}`;

            let newGroupMessage={
                group_id:group_id,
                user_id:user_id,
                types:1,
                time:new Date(),
                message:imageMessage,
            }
            //查找所有群成员socketid
            let groupMembers = await this.app.model.GroupMember.findAll({where:{group_id:group_id}});
            console.log("group_id",group_id)
            console.log(groupMembers);
            let groupMembersId=[];
            for(let i of groupMembers){
                groupMembersId.push(i.user_id);
            }
            console.log(groupMembersId)
            
            //存储群聊记录
            await this.app.model.GroupMessage.create(newGroupMessage);
            //将所有群成员未读消息数+1
            for(let id of groupMembersId){
                await this.app.model.GroupMember.update({lasttime:new Date()},{where:{group_id:group_id,user_id:id}});
                let groupMemberDeatil = await this.app.model.GroupMember.findOne({where:{group_id:group_id,user_id:id}});
                let tip = groupMemberDeatil.tip;
                console.log("+前",tip);
                let newTip=tip+1;
                console.log("+后",newTip);
                if(id!=user_id){
                  await this.app.model.GroupMember.update({tip:newTip},{where:{group_id:group_id,user_id:id}});  
                }
            }
            let message={
                //发送方信息
                user_id:user_id,
                user:{
                    name:name,
                    imgurl:imgurl
                },
                //接收方信息
                group_id:group_id,
                message:imageMessage
            }

            //向所有群成员推送消息推送信息
            for(let n of groupMembersId){
                let tokey=`user-${n}`;
                await app.io.of('/').sockets[users[tokey]].emit('groupRes',message);
            }

        }

        //好友文件传输
        async sendFriendFile(){
            const { ctx,app } = this;
            console.log("执行了")
            const file = ctx.request.files[0];//接收文件
            console.log("执行了呀呀呀呀呀呀")
            if (!file) return ctx.throw(404);
            console.log(file);
            let user_id = this.ctx.cookies.get('userid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let friend_id = this.ctx.cookies.get('friendid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let name = this.ctx.cookies.get('name',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let imgurl = this.ctx.cookies.get('imgurl',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })

            let tokey=`user-${friend_id}`;
            console.log("user[key]",users[tokey])

            const filename = file.filename;
            console.log("filename",filename);
            const targetPath = path.join(this.config.baseDir, `app/public/file`, filename);
            const source = fs.createReadStream(file.filepath);
            const target = fs.createWriteStream(targetPath);
            
            //上传图片到 public/avatar文件夹
            await pump(source, target);
            ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
            //将图片url存入数据库
            let fileMessage=`/file/${filename}`;

            //数据库存储聊天消息
            let newMessage={
                user_id:user_id,
                friend_id:friend_id,
                message:fileMessage,
                types:2,
                time:new Date(),
                state:1
            };
            await this.app.model.Message.create(newMessage);
            //将好友未读消息数+1
            let friendDetail=await this.app.model.Friend.findOne({where:{user_id:friend_id,friend_id:user_id}});
            let tip=friendDetail.tip
            console.log(tip)
            tip++;
            console.log(tip)
            await this.app.model.Friend.update({lasttime:new Date()},{ where:{$or:[{user_id:user_id,friend_id:friend_id},{user_id:friend_id,friend_id:user_id}]}});
            await this.app.model.Friend.update({tip:tip},{ where:{user_id:friend_id,friend_id:user_id}}); 
            console.log(tip)
            let message={
                //发送方信息
                user_id:user_id,
                user:{
                    name:name,
                    imgurl:imgurl
                },
                //接收方信息
                friend_id:friend_id,
                message:fileMessage
            }
            await app.io.of('/').sockets[users[`user-${user_id}`]].emit('friendRes',message);
            await app.io.of('/').sockets[users[tokey]].emit('friendRes',message);
            
        }

        //群聊文件传输
        async sendGroupFile(){
            const { ctx,app } = this;
            const file = ctx.request.files[0];//接收文件
            if (!file) return ctx.throw(404);

            let group_id = this.ctx.cookies.get('groupid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let user_id = this.ctx.cookies.get('userid',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let name = this.ctx.cookies.get('name',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })
            let imgurl = this.ctx.cookies.get('imgurl',{
                maxAge: 10000 * 1000,
                httpOnly: false,
                overwrite: true,
                signed: false,
            })

            // const filename = encodeURIComponent(ctx.request.body.name) + path.extname(file.filename).toLowerCase();
            const filename = file.filename;
            console.log("filename",filename)
            const targetPath = path.join(this.config.baseDir, `app/public/file`, filename);
            console.log("path",targetPath)
            const source = fs.createReadStream(file.filepath);
            const target = fs.createWriteStream(targetPath);
            
            //上传图片到 public/img文件夹
            await pump(source, target);
            ctx.logger.warn('save %s to %s', file.filepath, targetPath);  
            //将图片url存入数据库
            let fileMessage=`/file/${filename}`;

            let newGroupMessage={
                group_id:group_id,
                user_id:user_id,
                types:2,
                time:new Date(),
                message:fileMessage,
            }
            //查找所有群成员socketid
            let groupMembers = await this.app.model.GroupMember.findAll({where:{group_id:group_id}})
            console.log(groupMembers);
            let groupMembersId=[];
            for(let i of groupMembers){
                groupMembersId.push(i.user_id);
            }
            console.log(groupMembersId);
            //存储群聊记录
            await this.app.model.GroupMessage.create(newGroupMessage);
            //将所有群成员未读消息数+1
            for(let id of groupMembersId){
                await this.app.model.GroupMember.update({lasttime:new Date()},{where:{group_id:group_id,user_id:id}});
                let groupMemberDeatil = await this.app.model.GroupMember.findOne({where:{group_id:group_id,user_id:id}});
                let tip = groupMemberDeatil.tip;
                console.log("+前",tip);
                let newTip=tip+1;
                console.log("+后",newTip);
                if(id!=user_id){
                  await this.app.model.GroupMember.update({tip:newTip},{where:{group_id:group_id,user_id:id}}); 
                }
            }
            let message={
                //发送方信息
                user_id:user_id,
                user:{
                    name:name,
                    imgurl:imgurl
                },
                //接收方信息
                group_id:group_id,
                message:fileMessage
            }
            //向所有群成员推送消息推送信息
            for(let n of groupMembersId){
                let tokey=`user-${n}`;
                await app.io.of('/').sockets[users[tokey]].emit('groupRes',message);
            }
        }
    
        //断开连接
        async disconnect(){
            const { ctx, app } = this;
            const message = ctx.args[0];
            let userid = message.userid;
            console.log(userid);
            let key = `user-${userid}`;
            console.log(`用户user-${userid}离线了`)
            delete users[key]
            console.log(users)
        }

}

module.exports = chatControllerController;